package com.tjy.core;

import com.tjy.constant.Constant;
import com.tjy.util.HttpUtils;
import com.tjy.util.LogUtils;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * ClassName:DownloaderTask
 * Description:
 * author: jiuyang
 * DateTime: 2024/8/14 下午4:18
 */
public class DownloaderTask implements Callable<Boolean> {

    private String url;
    private long startPos;
    private long endPos;
    private CountDownLatch countDownLatch;
    //下载标识
    private int part;

    public DownloaderTask(String url, long startPos, long endPos, int part,CountDownLatch countDownLatch) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public Boolean call() throws Exception {
        //获取文件名
        String fileName = HttpUtils.getFileName(url);
        fileName = fileName + ".temp" + part;
        fileName = Constant.PATH + fileName;

        HttpURLConnection httpURLConnection = HttpUtils.getHttpURLConnection(url, startPos, endPos);

        try (InputStream input = httpURLConnection.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(input);
             RandomAccessFile accessFile = new RandomAccessFile(fileName, "rw")
        ) {

            byte[] buffer = new byte[Constant.BYTE_SIZE];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                //一秒内下载数据之和，通过原子类进行操作
                DownloaderInfo.downSize.add(len);
                accessFile.write(buffer, 0, len);
            }

        } catch (FileNotFoundException e) {
            LogUtils.error("找不到文件{}", fileName);
            return false;
        } catch (Exception e) {
            LogUtils.error("下载失败");
            return false;
        } finally {
            httpURLConnection.disconnect();
            countDownLatch.countDown();
        }


        return true;
    }
}
